package com.yuezhi.acl.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuezhi.acl.entity.SysPermission;
import com.yuezhi.acl.entity.SysRolePermission;
import com.yuezhi.acl.entity.SysUser;
import com.yuezhi.acl.helper.MemuHelper;
import com.yuezhi.acl.mapper.SysPermissionMapper;
import com.yuezhi.acl.service.SysPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuezhi.acl.service.SysRolePermissionService;
import com.yuezhi.acl.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author boys
 * @since 2020-12-16
 */
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {

    @Autowired
    private SysRolePermissionService rolePermissionService;

    @Autowired
    private SysUserService userService;

    //获取全部菜单
    @Override
    public List<SysPermission> queryAllMenu() {
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        List<SysPermission> sysPermissions = baseMapper.selectList(queryWrapper);
        List<SysPermission> result = bulid(sysPermissions);
        return result;
    }

    //根据角色获取菜单
    @Override
    public List<SysPermission> selectAllMenu(String roleId) {
        List<SysPermission> allPermissionsList = baseMapper.selectList(new QueryWrapper<SysPermission>().orderByDesc("CAST(id AS SIGNED)"));
        //根据角色id获取角色权限
        List<SysRolePermission> rolePermissionList = rolePermissionService.list(new QueryWrapper<SysRolePermission>().eq("role_id", roleId));

        for (int i = 0; i < allPermissionsList.size(); i++) {
            SysPermission sysPermission = allPermissionsList.get(i);
            for (int j = 0; j < rolePermissionList.size(); j++) {
                SysRolePermission rolePermission = rolePermissionList.get(j);
                if(rolePermission.getPermissionId().equals(sysPermission.getId())){
                    sysPermission.setSelect(true);
                }
            }
        }
        List<SysPermission> permissionList = bulid(allPermissionsList);
        return permissionList;
    }

    //给角色分配权限
    @Override
    public void saveRolePermissionRealtionShip(String roleId, String[] permissionId) {
        //roleId角色id
        //permissionId菜单id 数组形式
        //1 创建list集合，用于封装添加数据
        List<SysRolePermission> rolePermissions = new ArrayList<>();
        //遍历所有菜单数组
        for (String aLong : permissionId) {
            if (StringUtils.isEmpty(aLong)) continue;
            //RolePermission对象
            SysRolePermission rolePermission = new SysRolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(aLong);
            //封装到list集合
            rolePermissions.add(rolePermission);
        }
        //添加到角色菜单关系表
        rolePermissionService.saveBatch(rolePermissions);
    }

    //============递归删除菜单==================================
    @Override
    public void removeChildById(String id) {
        List<String> idList = new ArrayList<>();
        this.selectChildListById(id, idList);
        idList.add(id);
        baseMapper.deleteBatchIds(idList);
    }


    //根据用户id获取用户菜单
    @Override
    public List<String> selectPermissionValueByUserId(String id) {
        List<String> permissionValueList = null;
        if (this.isSysAdmin(id)) {
            //如果是系统管理员，获取所有权限
            permissionValueList = baseMapper.selectAllPermissionValue();
        } else {
            permissionValueList = baseMapper.selectPermissionValueByUserId(id);
        }
        return permissionValueList;
    }

    @Override
    public List<JSONObject> selectPermissionByUserId(String id) {
        List<SysPermission> permissionList = null;
        if(this.isSysAdmin(id)){
            //如果是系统管理员，获取所有菜单
            permissionList=baseMapper.selectList(null);
        }else{
            permissionList=baseMapper.selectPermissionByUserId(id);
        }
        List<SysPermission> permissionList1= bulid(permissionList);
        List<JSONObject> result = MemuHelper.bulid(permissionList1);
        return result;

    }
//=========================================================================

    /**
     * 判断用户是否系统管理员
     *
     * @param userId
     * @return
     */
    private boolean isSysAdmin(String userId) {
        SysUser user = userService.getById(userId);
        if (null != user && "admin".equals(user.getUsername())) {
            return true;
        }
        return false;
    }

    /**
     * 递归获取子节点
     *
     * @param id
     * @param idList
     */
    private void selectChildListById(String id, List<String> idList) {
        List<SysPermission> permissionList = baseMapper.selectList(new QueryWrapper<SysPermission>().eq("pid", id).select("id"));
        permissionList.stream().forEach(item -> {
            idList.add(item.getId());
            this.selectChildListById(item.getId(), idList);
        });
    }

    /**
     * 使用递归方法建菜单
     *
     * @param treeNodes
     * @return
     */
    private static List<SysPermission> bulid(List<SysPermission> treeNodes) {
        List<SysPermission> trees = new ArrayList<>();
        for (SysPermission treeNode : treeNodes) {
            if ("0".equals(treeNode.getPid())) {
                treeNode.setLevel(1);
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    private static SysPermission findChildren(SysPermission treeNode, List<SysPermission> treeNodes) {
        treeNode.setChildren(new ArrayList<SysPermission>());

        for (SysPermission it : treeNodes) {
            if (treeNode.getId().equals(it.getPid())) {
                int level = treeNode.getLevel() + 1;
                it.setLevel(level);
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }

    //把返回所有菜单list集合进行封装的方法
    public static List<SysPermission> bulidPermission(List<SysPermission> permissionList) {

        //创建list集合，用于数据最终封装
        List<SysPermission> finalNode = new ArrayList<>();
        //把所有菜单list集合遍历，得到顶层菜单 pid=0菜单，设置level是1
        for (SysPermission permissionNode : permissionList) {
            //得到顶层菜单 pid=0菜单
            if ("0".equals(permissionNode.getPid())) {
                //设置顶层菜单的level是1
                permissionNode.setLevel(1);
                //根据顶层菜单，向里面进行查询子菜单，封装到finalNode里面
                finalNode.add(selectChildren(permissionNode, permissionList));
            }
        }
        return finalNode;
    }

    private static SysPermission selectChildren(SysPermission permissionNode, List<SysPermission> permissionList) {
        //1 因为向一层菜单里面放二层菜单，二层里面还要放三层，把对象初始化
        permissionNode.setChildren(new ArrayList<SysPermission>());

        //2 遍历所有菜单list集合，进行判断比较，比较id和pid值是否相同
        for (SysPermission it : permissionList) {
            //判断 id和pid值是否相同
            if (permissionNode.getId().equals(it.getPid())) {
                //把父菜单的level值+1
                int level = permissionNode.getLevel() + 1;
                it.setLevel(level);
                //如果children为空，进行初始化操作
                if (permissionNode.getChildren() == null) {
                    permissionNode.setChildren(new ArrayList<SysPermission>());
                }
                //把查询出来的子菜单放到父菜单里面
                permissionNode.getChildren().add(selectChildren(it, permissionList));
            }
        }
        return permissionNode;
    }

    // 根据当前菜单id，查询菜单里面子菜单id，封装到list集合
    private void selectPermissionChildById(String id, List<String> idList) {
        //查询菜单里面子菜单id
        QueryWrapper<SysPermission> wrapper = new QueryWrapper<>();
        wrapper.eq("pid", id);
        wrapper.select("id");
        List<SysPermission> childIdList = baseMapper.selectList(wrapper);
        //把childIdList里面菜单id值获取出来，封装idList里面，做递归查询
        childIdList.stream().forEach(item -> {
            //封装idList里面
            idList.add(item.getId());
            //递归查询
            this.selectPermissionChildById(item.getId(), idList);
        });
    }
    //===================================================================================
}
